package com.chushouya.common.util;

import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Strings;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 订单工具类
 */
@Slf4j
public class OrderUtil {

    public static String getOrderNo() {
        String orderNo = Strings.format("{}{}{}", "S", Dates.dateTimeNow("yyMMddHHmmss"), ThreadLocalRandom.current().nextInt(100, 999)).toUpperCase();

        return orderNo;
    }

    /**
     * Java实体类转Map
     */
    public static Map<String, Object> entityToMap(Object obj){
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> clazz = obj.getClass();
        for(Field field : clazz.getDeclaredFields()){
            field.setAccessible(true);
            String fieldName = field.getName();
            Object object = null;
            try {
                object = field.get(obj);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                System.out.println(e.getMessage());
            }
            map.put(fieldName, object);
        }
        return map;
    }
    /**
     * 隐藏用户手机号
     */
    public static String hidePhone(String phone) {
        if (Strings.isBlank(phone)) {
            return "";
        }
        //如果不是11位手机号，直接返回
        if (phone.length() != 11) {
            return phone;
        }
        return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }
    /**
     * 将用户请求转换为Map
     */
    public static Map<String, String> requestToMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        return params;
    }
    /**
     * 获取当天剩余的时间，单位：秒
//     */
    public static Long getTodayRemainSecondNum() {
        long current = System.currentTimeMillis();    //当前时间毫秒数
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        long tomorrowZero = calendar.getTimeInMillis();
        return (tomorrowZero - current) / 1000;
    }
    /**
     * 获取当月剩余的天数，单位：天
     */
    public static Integer getMonthRemainDayNum() {
        Calendar calendar = Calendar.getInstance();
        int day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        int today = calendar.get(Calendar.DAY_OF_MONTH);
        return day - today;
    }

    public static String time2week(Date time) {
        switch (Dates.getDayOfWeek(time)) {
            case 0:
                return "周日";
            case 1:
                return "周一";
            case 2:
                return "周二";
            case 3:
                return "周三";
            case 4:
                return "周四";
            case 5:
                return "周五";
            case 6:
                return "周六";
        }
        return Strings.EMPTY;
    }
    /**
     * 自动派单时间校验
     */

    public static boolean autoDispatchTimeValidate(Date currentTime, String timeScopeStart, String timeScopeEnd) {
        Date start = Dates.parseDate(Strings.format("{} {}:00", Dates.format(currentTime, Dates.FMT_YYYY_MM_DD), timeScopeStart), Dates.FMT_FULL_TIME);
        Date end = Dates.parseDate(Strings.format("{} {}:00", Dates.format(currentTime, Dates.FMT_YYYY_MM_DD), timeScopeEnd), Dates.FMT_FULL_TIME);
        log.info("自动派单==>当前时间为:{}", Dates.format(currentTime, Dates.FMT_FULL_TIME));
        if (start.compareTo(end) == 0) {
            // 00 00
            log.info("自动派单==>[{} ~ {}]无效的时间区间", Dates.format(start, Dates.FMT_FULL_TIME), Dates.format(end, Dates.FMT_FULL_TIME));
            return false;
        } else if (start.compareTo(end) > 0) {
            //21 09
            //两个区间 00-09 21-00
            Date scope1Start = Dates.getFirstTime(currentTime);
            Date scope1End = end;
            Date scope2Start = start;
            Date scope2End = Dates.getLastTime(currentTime);
            log.info("自动派单==>时间区间:[{} ~ {}] [{} ~ {}]", Dates.format(scope1Start, Dates.FMT_FULL_TIME), Dates.format(scope1End, Dates.FMT_FULL_TIME),
                    Dates.format(scope2Start, Dates.FMT_FULL_TIME), Dates.format(scope2End, Dates.FMT_FULL_TIME));
            if (scope1Start.getTime() <= currentTime.getTime() && scope1End.getTime() >= currentTime.getTime()) {
                return true;
            }
            if (scope2Start.getTime() <= currentTime.getTime() && scope2End.getTime() >= currentTime.getTime()) {
                return true;
            }
        } else {
            // 09 21
            log.info("自动派单==>时间区间:[{} ~ {}]", Dates.format(start, Dates.FMT_FULL_TIME), Dates.format(end, Dates.FMT_FULL_TIME));
            if (start.getTime() <= currentTime.getTime() && end.getTime() >= currentTime.getTime()) {
                return true;
            }
        }
        return false;
    }

}
